package com.lxm.framework.web.jsonresult;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.jackson.JsonComponent;
import org.springframework.boot.jackson.JsonObjectSerializer;

import java.io.IOException;

/**
 * @author twenty2
 */
@Slf4j
@JsonComponent
public class JsonResultSerializer extends JsonObjectSerializer<JsonResult> {
    @Override
    protected void serializeObject(JsonResult jsonResult, JsonGenerator jgen, SerializerProvider provider) {
        var srcCodec = (ObjectMapper) jgen.getCodec();
        var newCode = srcCodec.copy();
        var jsonResultProvider = jsonResult.getJsonResultProvider();
        if (jsonResultProvider != null) {
            newCode.setFilterProvider(jsonResultProvider);
            newCode.setMixInResolver(jsonResult.getSimpleMixInResolver());
        }
        jgen.setCodec(newCode);
        String sign = jsonResult.getSign();
        try {
            jgen.writeFieldName("code");
            jgen.writeNumber(jsonResult.getCode());
            jgen.writeFieldName("message");
            jgen.writeString(jsonResult.getMessage());
            jgen.writeFieldName("data");
            jgen.writeObject(jsonResult.getData());
            if (StringUtils.isNotBlank(sign)) {
                jgen.writeFieldName("sign");
                jgen.writeObject(sign);
            }
        } catch (IOException e) {
            log.error("jsonResult serializer jgen write error", e);
        }
        jgen.setCodec(srcCodec);

    }
}
